#!/usr/bin/python2.5
#
# Copyright (c) 2009 Digital Darkness
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Wave PHPify robot handler.

When the robot is added to a wave, saves a copy of the wave to GAE datastore for
later retrieval as a PHP serialized object.
"""

__author__ = 'omni@digitaldarkness.com (Omni Adams)'

import logging
from waveapi import events
from waveapi import model
from waveapi import robot
from google.appengine.ext import db
import wave_model


def OnParticipantsChanged(properties, context):
  """Invoked when any participants have been added/removed.
 
  Args:
    properties:
    context
  """
  added = properties['participantsAdded']
  for p in added:
    Notify(context)


def OnBlipDeleted(properties, context):
  """Invoked when a blip is deleted.
 
  Args:
    properties:
    context:
  """
  logging.info('Blip "%s" was deleted.', properties['blipId'])


def OnBlipSubmitted(properties, context):
  """Invoked when a blip is submitted.

  Args:
    properties:
    context:
  """
  blip = context.GetBlipById(properties['blipId'])
  SaveBlip(blip, context.GetRootWavelet().GetTitle(), context)


def SaveBlip(blip, title, context):
  """Save a blip to the datastore.
 
  Args:
    blip: Blip model
    title: Wave title
    context:
  """
  if not blip:
    return
  query = wave_model.Wave.all()
  query.filter('blip_id =', blip.GetId())
  try:
    wave = query[0]
  except IndexError:
    # Blip doesn't already exist, create a new blip
    wave = wave_model.Wave()
    wave.blip_id = blip.GetId()
    wave.wave_id = blip.GetWaveId()
  wave.content = blip.GetDocument().GetText()
  wave.creator = blip.GetCreator()
  wave.parent_blip = blip.GetParentBlipId()
  wave.title = title
  wave.put()

  children = blip.GetChildBlipIds()
  for child in children:
    SaveBlip(context.GetBlipById(child), title, context)

  
def OnRobotAdded(properties, context):
  """Invoked when the robot has been added to a wave.
  
  Args:
    properties:
    context:
  """
  root_wavelet = context.GetRootWavelet()
  title = root_wavelet.GetTitle()

  for blip in context.GetBlips():
    SaveBlip(blip, title, context)


def OnTitleChanged(properties, context):
  """Invoked when the title to a wave is changed.
 
  Args:
    properties:
    context:
  """
  root_wavelet = context.GetRootWavelet()
  title = root_wavelet.GetTitle()
  for blip in context.GetBlips():
    SaveBlip(blip, title, context)


def Notify(context):
  """Notifies the wave that the robot has been added and its PHP URL.
 
  Args:
    context:
  """
  root_wavelet = context.GetRootWavelet()
  message = ("Hi everybody, I've PHPified this blip at "
             'http://phpify.appspot.com/%s') % root_wavelet.GetWaveId()
  root_wavelet.CreateBlip().GetDocument().SetText(message)


if __name__ == '__main__':
  bot = robot.Robot('phpify', 
      image_url='http://phpify.appspot.com/static/phpify.png',
      version='7',
      profile_url='http://phpify.appspot.com/')
  bot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED,
                      OnParticipantsChanged)
  bot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
  bot.RegisterHandler(events.BLIP_DELETED, OnBlipDeleted)
  bot.RegisterHandler(events.WAVELET_BLIP_CREATED, OnBlipSubmitted)
  bot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  bot.RegisterHandler(events.WAVELET_TITLE_CHANGED, OnTitleChanged)
  bot.Run()
